package session

import (
	"log"

	"test.com/fusion"
)

var InstLoginServerMgr *LoginServerManager

type LoginServerSession struct {
	fusion.Session
	IsReady bool
	lsSN    uint32
}

type LoginServerInstance struct {
	lsSession *LoginServerSession
}

type LoginServerManager struct {
	lsInstMap map[uint32]*LoginServerInstance
	lsSN      uint32
}

func NewLoginServerManagerInstance() {
	InstLoginServerMgr = &LoginServerManager{}
	InstLoginServerMgr.lsInstMap = make(map[uint32]*LoginServerInstance)
}

func (mgr *LoginServerManager) RegisterLoginServer(session *LoginServerSession) error {
	mgr.lsSN += 1
	session.lsSN, session.IsReady = mgr.lsSN, true
	mgr.lsInstMap[mgr.lsSN] = &LoginServerInstance{lsSession: session}
	log.Printf("register login server `%s`.`%d` successfully.\n", session, mgr.lsSN)
	return nil
}

func (mgr *LoginServerManager) UnregisterLoginServer(session *LoginServerSession) error {
	log.Printf("unregister login server `%s`.`%d`.\n", session, session.lsSN)
	if session.lsSN != 0 {
		delete(mgr.lsInstMap, session.lsSN)
	}
	return nil
}

func (mgr *LoginServerManager) SendPacket2LoginServer(lsID uint32, pck *fusion.NetPacket) {
	if lsID != 0 {
		if lsInfo, isOK := mgr.lsInstMap[lsID]; isOK {
			lsInfo.lsSession.SendPacket(pck)
		}
	} else {
		for _, lsInfo := range mgr.lsInstMap {
			lsInfo.lsSession.SendPacket(pck)
		}
	}
}

func (mgr *LoginServerManager) SendAllGameServerInfos2LoginServer(lsID uint32) {
	mgr.SendPacket2LoginServer(0, InstGameServerMgr.BuildAllGameServerInfosPacket())
}
